local skel = fk.CreateSkill {
  name = "emo__linggan",
}

Fk:loadTranslationTable{
  ["emo__linggan"] = "灵感",
  [":emo__linggan"] = "出牌阶段，你可以亮出牌堆顶三张牌，你亮出一张手牌或一张“灵感”，令这些牌凑成三张点数相同、或三张同花色、或四张不同花色的组合，然后将符合条件的牌当<a href=':wish_fulfill'>【心想事成】</a>使用，若无符合牌，本阶段此技能无效。未使用的牌置于武将牌上称为“灵感”。",

  ["#emo__linggan"] = "灵感：亮出牌堆三张牌，再亮出你1张牌，进行组合！",
  ["lingganPile"] = "灵感",
  ["#emo__linggan-show"] = "灵感：请亮出一张手牌或一张“灵感”",

  ["$emo__linggan1"] = "啊！灵光乍现，想到个不错的剧本！",
  ["$emo__linggan2"] = "游戏～游戏～打游戏呀～想打游戏～",
}

--- 获取符合的类型组合
---@param cards integer[]
---@return integer[]?
local function getFitCards(cards)
  if #cards < 2 then return nil end
  local suitMap, numMap = {}, {}
  local suitNum = 0
  for _, cid in ipairs(cards) do
    local card = Fk:getCardById(cid)
    if suitMap[card.suit] == nil then
      suitMap[card.suit] = {cid}
      suitNum = suitNum + 1
    else
      table.insert(suitMap[card.suit], cid)
    end
    numMap[card.number] = numMap[card.number] or {}
    table.insert(numMap[card.number], cid)
  end
  -- 先检查对子
  for _, ids in pairs(numMap) do
    if #ids >= 3 then
      return table.slice(ids, 1, 4)
    end
  end
  -- 检查同花
  for _, ids in pairs(suitMap) do
    if #ids >= 3 then
      return table.slice(ids, 1, 4)
    end
  end
  -- 检查四种花色
  if suitNum == 4 then
    return table.simpleClone(cards)
  end
  return nil
end

skel:addEffect("active", {
  anim_type = "drawcard",
  card_num = 0,
  target_num = 0,
  prompt = "#emo__linggan",
  can_use = function (self, player)
    return true
  end,
  on_use = function (self, room, use)
    local player = use.from
    local cards = room:getNCards(3)
    room:moveCardTo(cards, Card.Processing, nil, fk.ReasonPut, skel.name)
    if not player:isNude() or #player:getPile("lingganPile") > 0 then
      local cid = room:askToCards(player, {
        min_num = 1, max_num = 1, skill_name = skel.name, pattern = ".|.|.|hand,lingganPile", cancelable = false, include_equip = false,
        expand_pile = "lingganPile", prompt = "#emo__linggan-show",
      })[1]
      if cid then
        table.insert(cards, cid)
        room:moveCardTo(cid, Card.Processing, nil, fk.ReasonPut, skel.name)
      end
    end
    room:delay(600)
    local win
    for _ = 1, 2 do
      if player.dead then break end
      local fit = getFitCards(cards)
      if not fit then break end
      win = true
      local card = Fk:cloneCard("wish_fulfill")
      card.skillName = skel.name
      card:addSubcards(fit)
      room:useCard{
        from = player, tos = {player}, card = card
      }
      cards = table.filter(cards, function (cid) return not table.contains(fit, cid) and room:getCardArea(cid) == Card.Processing end)
    end
    if not win then
      room:invalidateSkill(player, skel.name, "-phase")
    end
    if not player.dead and #cards > 0 then
      player:addToPile("lingganPile", cards, true, skel.name)
    end
    room:cleanProcessingArea(cards)
  end,
})

return skel
